'use strict';
const db = uniCloud.database();
const dbCmd = db.command;
const $ = dbCmd.aggregate;
exports.main = async (event, context) => {
	let type =event.type || -1//-1全部0当下1过往
	let selDate=event.selDate ||'' //发布日期
	let selDateRang=event.selDateRang ||''
	
	let obj={}
	if(type=='1'){//当下
		if(selDate!=''){
			obj={
				// memoryDate:dbCmd.and(dbCmd.gte('2020-08-23'), dbCmd.lte('2020-08-26')),
				publish_date:dbCmd.eq(selDate),
				classfy:1,
			}
		}else{
			obj={
				// memoryDate:dbCmd.and(dbCmd.gte('2020-08-23'), dbCmd.lte('2020-08-26')),
				classfy:1,
			}
		}
		
	}
	if(type==2){
		if(selDateRang){
			let date1 = selDateRang.split('至')[0]
			let date2 = selDateRang.split('至')[1]
			obj={
				memoryDate:dbCmd.and(dbCmd.gte(date1), dbCmd.lte(date2)),
				classfy:0,
			}
			if(selDate!=''){
				obj={
					memoryDate:dbCmd.and(dbCmd.gte(date1), dbCmd.lte(date2)),
					classfy:0,
					publish_date:dbCmd.eq(selDate),
				}
			}
		}else{
			obj={
				classfy:0,
				
			}
			if(selDate!=''){
				obj={
					classfy:0,
					publish_date:dbCmd.eq(selDate),
				}
			}
		}
		
	}
	console.log(event,obj)
	
	let page =event.page || 1
	let pageCount=event.pageCount || 2
	let skipC= (page - 1)*pageCount;
	let loginUser_id = event.user_id || ''
	let res =await db.collection('memory').aggregate()
	.match(obj)
	.lookup(
		{
			from:'uni-id-users',
			localField:'user_id',
			foreignField:'_id',
			as:'user_id'
		}
		
	).lookup({
			from:'watchLogs',
			localField:'_id',
			foreignField:'memoryId',
			as:'memoryWatchList'
		})
	.sort(
		{
			publish_dateTime:-1
		}
	)
	.project({
		// memoryWatchList:1,
		title:1,
		content:1,
		imgList:1,
		classfy:1,
		classfyLabel:1,
		canComment:1,
		memoryDate:1,
		publish_date:1,
		publish_dateTime:1,
		commentTotal:1,
		isPublic:1,
		'user_id':{
			nickName: 1,
			sex: 1,
			mobile:1,
			avatar:1
		  },
		watchCount:$.size('$memoryWatchList'),
		included:$.in([loginUser_id, '$quanxian'])
	}).end()
	
	// console.log(res,'res')
	return res
};
